from solvers.solverbase import SolverBase
from solvers.analytical.analyticalbase import AnalyticalBase
from dolfin import *

class BackwardEuler(SolverBase,AnalyticalBase):
    'Backward-Euler method.'
    def __init__(self,p=1):
        SolverBase.__init__(self,p)
        AnalyticalBase.__init__(self)

    def solve(self,problem):
        mesh = problem.domain

        p = self.p
        V = FunctionSpace(mesh,'CG',p)
        VV = VectorFunctionSpace(mesh,'CG',p)

        phi_ = interpolate(problem.phi_,V)
        phi = TrialFunction(V)
        varphi = TestFunction(V)

        t = problem.t           
        dt = Constant(SolverBase._get_time_step(self,problem,VV,t))
        T = problem.T

        v = SolverBase._get_velocity(self,problem,VV,t)
  

        (ib,ib_value,bParts) = problem.get_inflowBCS()                               ### NEW
        if problem.weakBC:
            a = phi*varphi*dx - dt*(inner(nabla_grad(varphi),v*phi)*dx + nabla_div(v)*phi*varphi*dx)
        else:
            n = FacetNormal(mesh)
            a = phi*varphi*dx + dt*(phi*varphi*inner(v,n)*ds(0) - inner(nabla_grad(varphi),v*phi)*dx - nabla_div(v)*phi*varphi*dx) 

        l = phi_*varphi*dx


        self.update(problem,phi_,t,float(dt),0)  # store the solution at time 0
       
        A = assemble(a,exterior_facet_domains=bParts)        # this is due to ds(0)term       ###NEW
        phi = Function(V)
   
        t = float(dt)
        count = 1

        while t <= T:
            L = assemble(l)  # v is not f(t), if it were, A has to be reassembled as well as L; no ds(0) term here!         ###NEW
            ibc = DirichletBC(V,ib_value(t),ib)  # apply the inflow boundary conditions                                        ###NEW
            ibc.apply(A,L)                                                                                                  ###NEW
            solve(A,phi.vector(),L)
            phi_.assign(phi)
            
            self.update(problem,phi_,t,float(dt),count)

            t += float(dt)
            count += 1

        problem.save_data(self.saveDir,str(self.CFL))

